import {login, getInfo, sendMsg} from '@/api/userLogin'

const user = {
  state: {
    city: {
      cityId: '',
      cityName: ''
    },
    selectShop: {
      shopId: '',
      shopName: '',
      shopAddress: ''
    },
    cart: [
    ]
  },

  mutations: {
    SET_CITY(state, city) {
      state.city = city
    },
    SET_SHOP(state, shop) {
      state.selectShop = shop
    },
    SET_CART(state, product) {
      state.cart.push(product)
    },
    addCart(state, item) {
      state.cart.push(item)
    },
    removeCart(state, pid) {
      let index = -1
      for (let i = 0; i < state.cart.length; i++) {
        if (state.cart[i].product.pid === pid) {
          index = i
          break
        }
      }
      if (index >= 0) {
        state.cart.splice(index, 1)
      }
    },
  },

  actions: {
    // 登录
    userLogin({commit}, userInfo) {
      const username = userInfo.userTel.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.userPw).then(data => {
          localStorage.setItem("token", data.userId)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    userGetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        let token = localStorage.getItem("token")
        getInfo(token).then(data => {
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 发送短信
    sendMsg({commit}, {openId, userTel}) {
      return new Promise((resolve, reject) => {
        sendMsg(openId, userTel).then(data => {
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
